package com.asp.alumnisystem.ui;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;

import com.asp.alumnisystem.R;
import com.asp.alumnisystem.adapter.FragmentPagerAdapter;
import com.asp.alumnisystem.app.App;
import com.asp.alumnisystem.base.BaseActivity;
import com.asp.alumnisystem.fragment.ForumFragment;
import com.asp.alumnisystem.fragment.FriendFragment;
import com.asp.alumnisystem.fragment.MyFragment;
import com.asp.alumnisystem.fragment.NoticeFragment;
import com.asp.alumnisystem.utils.ToastUtil;
import com.asp.alumnisystem.utils.UiUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 主界面 (论坛，公告，好友，我的)
 */
public class HomeActivity extends BaseActivity {

    @BindView(R.id.home_view_pager)
    ViewPager viewPager;

    @BindView(R.id.home_table_layout)
    TabLayout tabLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.home_layout;
    }

    @Override
    protected void initView() {
        super.initView();
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(this, getSupportFragmentManager(),
                getFragmentList(),UiUtils.getStringArray(App.getApp().isVisitor() ?
                R.array.home_title_arrays_visitor : R.array.home_title_arrays_user));
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        //初始化布局中下面导航栏界面
        for (int i = 0; i < adapter.getCount(); i++) {
            TabLayout.Tab layoutTabAt = tabLayout.getTabAt(i);
            View itemView = adapter.getTabItemView(i);
            layoutTabAt.setCustomView(itemView);
        }
    }

    /**
     * 加载fragment list
     */
    private List<Fragment> getFragmentList(){
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new ForumFragment());
        fragmentList.add(new NoticeFragment());
        if (!App.getApp().isVisitor()){
            fragmentList.add(new FriendFragment());
        }
        fragmentList.add(new MyFragment());
        return fragmentList;
    }

    @Override
    public void onBack() {
        twiceBackExit();
    }

    /**
     * 两次点击退出应用
     */
    private boolean isSecondBackPressed;
    private long firstTime;
    private void twiceBackExit() {
        if (isSecondBackPressed) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime < 2000) {
                this.finish();
            } else {
                firstTime = System.currentTimeMillis();
                ToastUtil.showShortToast(getString(R.string.twice_click_exit));
            }
        } else {
            isSecondBackPressed = true;
            firstTime = System.currentTimeMillis();
            ToastUtil.showShortToast(getString(R.string.twice_click_exit));
        }
    }
}
